package com.honeybees.framework.common.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * <DL>
 * <DT><B> AES加密工具 </B></DT>
 * <p>
 * <DD>详细介绍</DD>
 * </DL>
 * <p>
 *
 * @author liym
 * @since 2014-08-18 09:27:32
 */
public final class CryptoUtil {

    /**
     * This is an algorithm-specific metric, specified in number of bits.
     * <p>
     * 192 and 256 bits may not be available.
     */
    private static final int KEY_SIZE = 128;

    private final static String HEX = "0123456789abcdef";

    /**
     * <DL>
     * <DT><B> 加密 </B></DT>
     * <p>
     * <DD></DD>
     * </DL>
     * <p>
     *
     * @param plainText 明文（密码，5～15位字符，加密后32位）
     * @param seed      密钥
     * @return 密文
     * @throws Exception
     * @version 2014-08-18 09:30:24
     */
    public static String encrypt(String plainText, String seed) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(plainText.getBytes(), rawKey);

        return toHex(result);
    }

    /**
     * <DL>
     * <DT><B> 解密 </B></DT>
     * <p>
     * <DD></DD>
     * </DL>
     * <p>
     *
     * @param cipherText 密文
     * @param seed       密钥
     * @return 明文
     * @throws Exception
     * @version 2014-08-18 09:33:22
     */
    public static String decrypt(String cipherText, String seed) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] enByte = toByte(cipherText);

        byte[] result = decrypt(enByte, rawKey);
        return new String(result);
    }

    /**
     * <DL>
     * <DT><B> 标题 </B></DT>
     * <p>
     * <DD>详细介绍</DD>
     * </DL>
     * <p>
     *
     * @param seeds
     * @return
     * @throws Exception
     * @version 2014-08-18 09:29:35
     */
    private static byte[] getRawKey(byte[] seeds) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(seeds);
        kgen.init(KEY_SIZE, random); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();

        return skey.getEncoded();
    }

    /**
     * <DL>
     * <DT><B> 标题 </B></DT>
     * <p>
     * <DD>详细介绍</DD>
     * </DL>
     * <p>
     *
     * @param plainBytes
     * @param rawKey
     * @return
     * @throws Exception
     * @version 2014-08-18 09:44:39
     */
    private static byte[] encrypt(byte[] plainBytes, byte[] rawKey) throws Exception {
        SecretKeySpec sks = new SecretKeySpec(rawKey, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, sks);

        return cipher.doFinal(plainBytes);
    }

    /**
     * <DL>
     * <DT><B> 标题 </B></DT>
     * <p>
     * <DD>详细介绍</DD>
     * </DL>
     * <p>
     *
     * @param cipherBytes
     * @param rawKey
     * @return
     * @throws Exception
     * @version 2014-08-18 09:58:27
     */
    private static byte[] decrypt(byte[] cipherBytes, byte[] rawKey) throws Exception {
        SecretKeySpec sks = new SecretKeySpec(rawKey, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, sks);

        return cipher.doFinal(cipherBytes);
    }

    public static String toHex(String msg) {
        return toHex(msg.getBytes());
    }

    /**
     * <DL>
     * <DT><B> 标题 </B></DT>
     * <p>
     * <DD>详细介绍</DD>
     * </DL>
     * <p>
     *
     * @param bytes
     * @return
     * @version 2014-08-18 09:59:44
     * @see #toByte(String)
     */
    public static String toHex(byte[] bytes) {
        if (bytes == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder(2 * bytes.length);
        for (byte aByte : bytes) {
            appendHex(sb, aByte);
        }
        return sb.toString();
    }

    /**
     * <DL>
     * <DT><B> 标题 </B></DT>
     * <p>
     * <DD>详细介绍</DD>
     * </DL>
     * <p>
     *
     * @param sb
     * @param b
     * @version 2014-08-18 10:39:22
     */
    private static void appendHex(StringBuilder sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

    /**
     * <DL>
     * <DT><B> 标题 </B></DT>
     * <p>
     * <DD>详细介绍</DD>
     * </DL>
     * <p>
     *
     * @param hexString
     * @return
     * @version 2014-08-18 10:46:20
     * @see #toHex(byte[])
     * @see #toHex(String)
     */
    public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++) {
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        }
        return result;
    }

    /**
     * <DL>
     * <DT><B> 标题 </B></DT>
     * <p>
     * <DD>详细介绍</DD>
     * </DL>
     * <p>
     *
     * @param hexString
     * @return
     * @version 2014-08-18 10:47:28
     */
    public static String parseHex(String hexString) {
        return new String(toByte(hexString));
    }

    public static void main(String[] args) {
        String username = "ijLee89@163.com"; // 用户名
        String key = toHex(username); // 密钥
        System.out.println("Key: " + key);
        String password = "whats163Mail"; // 密码（明文，5～15位，加密后为32位）
        try {
            String cipherTxt = CryptoUtil.encrypt(password, key);
            System.out.println("加密结果：" + cipherTxt);
            String decryptingCode = CryptoUtil.decrypt(cipherTxt, key);
            System.out.println("解密结果：" + decryptingCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
